package com.hhsj.design.pullableview;

import android.util.Log;
import android.view.View;
import android.view.animation.Interpolator;

public abstract class FooterBackToNormalRunnable implements Runnable {
    private View mLoadMoreViewParent;
    private int mDuration;
    private boolean mIsFinish;
    private long mStartTime;

    private Interpolator mInterpolator = input -> (float) Math.pow(input, 0.5);

    public FooterBackToNormalRunnable(View refreshView) {
        mLoadMoreViewParent = refreshView;
        mIsFinish = true;
    }

    public void start(int duration) {
        mDuration = duration;
        mLoadMoreViewParent.removeCallbacks(this);
        if (mIsFinish) {
            mStartTime = System.currentTimeMillis();
            mIsFinish = false;
            mLoadMoreViewParent.post(this);
            onFooterBackNormalStart();
        }
    }

    public void cancel() {
        this.mIsFinish = true;
    }

    @Override
    public void run() {
        if (!mIsFinish) {
            long delta = System.currentTimeMillis() - mStartTime;
            if (delta > mDuration) {
                delta = mDuration;
            }
            float param = mInterpolator.getInterpolation(1f - delta * (1f / mDuration));
            Log.e("HHSJ", param+" ");
//            int movedHeight = (int) ((mRefreshView.getLoadMoreView().getY() + mRefreshViewHeight) * param);
            int movedHeight = (int) (mLoadMoreViewParent.getMeasuredHeight() * param);
            if (movedHeight <= 0) {
                updateFooterLayoutHeight(0);
                mIsFinish = true;
                onFooterBackNormalCompleted();//mIsRefresh = false;
            } else {
                updateFooterLayoutHeight(movedHeight);
                mLoadMoreViewParent.post(this);
            }
        }
    }

    /**
     * 更新刷新布局的高度
     *
     * @param movedHeight
     */
    public abstract void updateFooterLayoutHeight(int movedHeight);

    public abstract void onFooterBackNormalStart();

    /**
     * 标记回归到正常
     */
    protected abstract void onFooterBackNormalCompleted();


}